package com.ycrlkj.android.modulescore.main.activity;

import androidx.annotation.ChecksSdkIntAtLeast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.os.EnvironmentCompat;
import androidx.lifecycle.ViewModelProvider;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.android.arouter.utils.TextUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.ycrlkj.android.modulescore.main.apiservice.DictValueApiService;
import com.ycrlkj.android.modulescore.main.entity.DictValue;
import com.ycrlkj.android.modulescore.main.entity.validate.VehicleValidate;
import com.ycrlkj.android.modulescore.main.viewmodel.VehicleRegisterViewModel;
import com.ycrlkj.android.modulespublic.common.base.MArrayAdapter;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiException;
import com.ycrlkj.android.modulespublic.common.net.exception.ApiExceptionHandler;
import com.ycrlkj.android.modulespublic.common.net.exception.ErrorConsumer;
import com.ycrlkj.android.modulespublic.common.net.transformer.ResponseTransformer;
import com.ycrlkj.android.modulescore.main.apiservice.VehicleApiService;
import com.ycrlkj.android.modulescore.main.databinding.ActivityVehicleRegisterBinding;
import com.ycrlkj.android.modulescore.main.entity.Vehicle;
import com.ycrlkj.android.modulespublic.common.constant.RoutePath;
import com.ycrlkj.android.modulespublic.common.utils.xpopup.XPopupUtil;
import com.ycrlkj.android.modulespublic.common.widget.titlebar.MTitleBar;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;
import io.reactivex.functions.Consumer;

@AndroidEntryPoint
@Route(path = RoutePath.PAGE_VEHICLE_REGISTER)
public class VehicleRegisterActivity extends AppCompatActivity {

    private ActivityVehicleRegisterBinding binding;

    private VehicleRegisterViewModel viewModel;

    @Inject
    VehicleApiService vehicleApiService;

    @Inject
    DictValueApiService dictValueApiService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);
        binding = ActivityVehicleRegisterBinding.inflate(getLayoutInflater());
        viewModel = new ViewModelProvider(this).get(VehicleRegisterViewModel.class);
        binding.setViewModel(viewModel);
        binding.setLifecycleOwner(this);

        setContentView(binding.getRoot());

        initTitleBar();

        initSelectPlateColor();
        initSelectVehicleSpecification();
    }

    @SuppressLint({"CheckResult", "SimpleDateFormat"})
    public void handleSave(View view) {
        Vehicle form = new Vehicle();

        form.setBrandName(viewModel.getBrandName().getValue());
        form.setModelName(viewModel.getModelName().getValue());
        form.setPlateNum(viewModel.getPlateNum().getValue());
        form.setDrivingCode(viewModel.getDrivingCode().getValue());
        form.setTransportationCode(viewModel.getTransportationCode().getValue());

        //校验表单
        String msg = VehicleValidate.validateForm(form);
        if (msg != null) {
            ToastUtils.showLong(msg);
            return;
        }

        if (viewModel.getPlateColorPosition().getValue() == 0) {
            ToastUtils.showLong("请选择车牌颜色");
            return;
        }
        form.setPlateColor(viewModel.getPlateColorValueArr().getValue()[viewModel.getPlateColorPosition().getValue()]);


        if (viewModel.getVehicleSpecificationPosition().getValue() == 0) {
            ToastUtils.showLong("请选择车辆规格");
            return;
        }
        form.setSpecification(viewModel.getVehicleSpecificationValueArr().getValue()[viewModel.getVehicleSpecificationPosition().getValue()]);

        String buyTime = viewModel.getBuyTime().getValue();
        if (TextUtils.isEmpty(buyTime)) {
            ToastUtils.showLong("请选择购买年份");
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(buyTime);
            if (date != null) {
                buyTime = sdf1.format(date);
            } else {
                buyTime = null;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            ToastUtils.showLong("时间格式处理错误");
        }

        if (buyTime != null) {
            form.setBuyTime(buyTime);
        }

        String userId = SPStaticUtils.getString("userId");
        if (!TextUtils.isEmpty(userId))
            form.setById(userId);

        LoadingPopupView loadingPopupView = XPopupUtil.showLoading(this, "提交中...");
        XPopupUtil.hideLoadingDelay(loadingPopupView);

        vehicleApiService.register(form)
                .compose(ResponseTransformer.obtain())
                .subscribe(resultData -> {
                    XPopupUtil.hideLoading(loadingPopupView);
                    XPopupUtil.showAlert(VehicleRegisterActivity.this, resultData.getToast());
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        XPopupUtil.hideLoading(loadingPopupView);
                        ApiExceptionHandler.doWith(VehicleRegisterActivity.this, e);
                    }
                });
    }


    public void initTitleBar() {
        MTitleBar mTitleBar = binding.mTitleBar;
        mTitleBar.setBtnEvents(new MTitleBar.BtnEvents() {
            @Override
            public void setBtnLeftOnClickListener() {
                finish();
            }

            @Override
            public void setBtnRightOnClickListener() {
            }
        });
    }

    @SuppressLint("CheckResult")
    public void initSelectVehicleSpecification() {
        dictValueApiService.getAllByDictFieldName("vehicle_specification")
                .compose(ResponseTransformer.obtain())
                .subscribe(dictValues -> {
                    int size = dictValues.size() + 1;

                    String[] textArr = new String[size];
                    int[] valueArr = new int[size];

                    for (int i = 0; i < size; i++) {
                        if (i == 0) {
                            textArr[i] = "无";
                            valueArr[i] = -1;
                        } else {
                            textArr[i] = dictValues.get(i - 1).getText();
                            valueArr[i] = dictValues.get(i - 1).getValue();
                        }
                    }

                    viewModel.getVehicleSpecificationValueArr().setValue(valueArr);
                    viewModel.getVehicleSpecificationTextArr().setValue(textArr);

                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        ApiExceptionHandler.doWith(VehicleRegisterActivity.this, e);
                    }
                });
    }

    public void handleSelectVehicleSpecification(View view) {
        String[] arr = viewModel.getVehicleSpecificationTextArr().getValue();
        Integer defaultChecked = viewModel.getVehicleSpecificationPosition().getValue();
        XPopupUtil.showSelect(this, "车型", arr, defaultChecked, new OnSelectListener() {
            @Override
            public void onSelect(int position, String text) {
                viewModel.getVehicleSpecificationPosition().setValue(position);
                viewModel.getVehicleSpecificationText().setValue(text);
            }
        });
    }

    @SuppressLint("CheckResult")
    public void initSelectPlateColor() {
        dictValueApiService.getAllByDictFieldName("vehicle_plate_color")
                .compose(ResponseTransformer.obtain())
                .subscribe(dictValues -> {
                    int size = dictValues.size() + 1;

                    String[] textArr = new String[size];
                    int[] valueArr = new int[size];

                    for (int i = 0; i < size; i++) {
                        if (i == 0) {
                            textArr[i] = "无";
                            valueArr[i] = -1; //这里指的是数据库存的value 的int值, 不是数组元素索引, 此元素索引为0, 在下拉选择框中是第一个无意义占位框, int值为了不与其它值冲突, 设为-1
                        } else {
                            textArr[i] = dictValues.get(i - 1).getText();
                            valueArr[i] = dictValues.get(i - 1).getValue();
                        }
                    }

                    viewModel.getPlateColorValueArr().setValue(valueArr);
                    viewModel.getPlateColorTextArr().setValue(textArr);
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        ApiExceptionHandler.doWith(VehicleRegisterActivity.this, e);
                    }
                });

    }

    public void handleSelectPlateColor(View view) {
        String[] arr = viewModel.getPlateColorTextArr().getValue();
        Integer defaultChecked = viewModel.getPlateColorPosition().getValue();
        XPopupUtil.showSelect(this, "车牌颜色", arr, defaultChecked, new OnSelectListener() {
            @Override
            public void onSelect(int position, String text) {
                viewModel.getPlateColorPosition().setValue(position);
                viewModel.getPlateColorText().setValue(text);
            }
        });
    }

    public void handleSelectBuyTime(View view) {
        String[] arr = viewModel.getBuyTimeArr().getValue();
        Integer defaultChecked = viewModel.getBuyTimePosition().getValue();
        XPopupUtil.showSelect(this, "购买时间", arr, defaultChecked, new OnSelectListener() {
            @Override
            public void onSelect(int position, String text) {
                viewModel.getBuyTimePosition().setValue(position);
                viewModel.getBuyTime().setValue(text);
            }
        }, 1200);
    }

    public void handlePhoto(View view) {
        XPopupUtil.showAlert(this, "请横置手机拍照, 让车身完全在取景框内", new OnConfirmListener() {
            @Override
            public void onConfirm() {
                checkPermissionAndCamera();
            }
        });
    }

    //用于保存拍照图片的uri
    private Uri mCameraUri;

    // 用于保存图片的文件路径，Android 10以下使用图片路径访问图片
    private String mCameraImagePath;

    // 是否是Android 10以上手机
    @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.Q)
    private final boolean isAndroidQ = Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q;

    // 申请相机权限的requestCode
    private static final int PERMISSION_CAMERA_REQUEST_CODE = 0x00000012;

    /**
     * 检查权限并拍照。
     * 调用相机前先检查权限。
     */
    private void checkPermissionAndCamera() {
        int hasCameraPermission = ContextCompat.checkSelfPermission(getApplication(), Manifest.permission.CAMERA);
        if (hasCameraPermission == PackageManager.PERMISSION_GRANTED) {
            openCamera();
        } else {
            //没有权限，申请权限。
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSION_CAMERA_REQUEST_CODE);
        }
    }

    /**
     * 处理权限申请的回调。
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_CAMERA_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //允许权限，有调起相机拍照。
                openCamera();
            } else {
                //拒绝权限，弹出提示框。
                ToastUtils.showLong("拍照权限被拒绝");
            }
        }
    }


    /**
     * 调起相机拍照
     */
    @SuppressLint("QueryPermissionsNeeded")
    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断是否有相机
        if (intent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            Uri photoUri = null;

            if (isAndroidQ) {
                // 适配android 10
                photoUri = createImageUri();
            } else {
                try {
                    photoFile = createImageFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (photoFile != null) {
                    mCameraImagePath = photoFile.getAbsolutePath();
                    //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
                    photoUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", photoFile);
                }
            }

            mCameraUri = photoUri;
            if (photoUri != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivityForResult(intent, PERMISSION_CAMERA_REQUEST_CODE);
            }
        }
    }

    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     */
    private Uri createImageUri() {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }

    /**
     * 创建保存图片的文件
     */
    private File createImageFile() throws IOException {
        String imageName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        File tempFile = new File(storageDir, imageName);
        if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
            return null;
        }
        return tempFile;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PERMISSION_CAMERA_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                if (isAndroidQ) {
                    // Android 10 使用图片uri加载
                    binding.vehiclePhoto.setImageURI(mCameraUri);
                } else {
                    // 使用图片路径加载
                    binding.vehiclePhoto.setImageBitmap(BitmapFactory.decodeFile(mCameraImagePath));
                }
            } else {
                ToastUtils.showLong("已取消操作");
            }
        }
    }

}